﻿using com.youzu.got.protocol;
using System;
using System.Collections.Generic;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Profiling;
using UnityEngine.UI;
using XLua;
using Yoozoo.Framework.Managers;

namespace Yoozoo.Gameplay.RTS
{
    public class RTSMono : MonoBehaviour
    {

        public static RTSMono Instance;
        public int time;
        private LuaFunction _luaUpdate;
        private LuaFunction _luaUpdateSecond;
        //private LuaFunction _luaMarchTestUpdate;
        private FlyTextManager _flyTextManager;
        private float _lastUpdateTime;
        public float StandardSoldierScale = 0.045f;
        public float ScaleFactor = 3.85f;
        public float SoldierScale => StandardSoldierScale * ScaleFactor;

        [CSharpCallLua]
        private delegate void _LuaUpdate(float time, long serverTime);

        ProfilerMarker MarchManagerUpdate = new ProfilerMarker("[C#]MarchManager.Update");
        ProfilerMarker ResourceManagerUpdate = new ProfilerMarker("[C#]ResourceManager.Update");
        ProfilerMarker ElementhManagerUpdate = new ProfilerMarker("[C#]ElementManager.Update");
        ProfilerMarker UpdateEverySecondMarker = new ProfilerMarker("G_MarchManager.UpdateEverySecond");
        ProfilerMarker luaMarchManagerUpdateMarker = new ProfilerMarker("[Lua]MarchManager.Update");
#if UNITY_EDITOR
        [Header("调试小兵信息")][NonSerialized]
        public bool IsShowEdidorButton = false;
        private float tempScale;
        
        [HideInInspector][NonSerialized]
        public bool isChanged = false;
        public bool FixTradeTruckPath = true;
#endif
        // Use this for initialization
        private ShakeScreen shakeScreen;
        public void ShakeScreen()
        {
            shakeScreen.Shake();
        }

        public void StopShakeScreen()
        {
            shakeScreen.StopShake();
        }
        
        void Start()
        {
            Instance = this;
            if (RTSUnitTest.Enable)
            {
                gameObject.AddComponent<RTSUnitTest>();
            }
            shakeScreen = gameObject.AddComponent<ShakeScreen>();
        }
        private bool isDisableUpdate = false;
        // Update is called once per frame
        void Update()
        {
            if (RTSLuaCallCSharpManager.isArmyEnabled && isDisableUpdate)
            {
                isDisableUpdate = false;
                SquareDataManager.Instance.ForceSetMarchStatusAll();
            }

            if (isDisableUpdate)
            {
                return;
            }
            if (ArmyManager.Instance == null)
            {
                return;
            }
            var _ct = TimeUtils.GetClientTickTime();
            if (_flyTextManager == null)
            {
                _flyTextManager = new FlyTextManager();
                _flyTextManager.Init();
            }
            
            MarchManagerUpdate.Begin();
            ArmyManager.Instance.MarchManager?.Update();
            MarchManagerUpdate.End();

            ResourceManagerUpdate.Begin();
            ArmyManager.Instance.ResourceManager?.Update();
            ResourceManagerUpdate.End();

            ElementhManagerUpdate.Begin();
            ArmyManager.Instance.ElementManager?.Update();
            ElementhManagerUpdate.End();

            if (_luaUpdate == null)
            {
                _luaUpdate = LuaManager.mainState.GetFunction("G_MarchManager.Update");
            }
    
            UpdateEverySecondMarker.Begin();
            if (_luaUpdateSecond == null)
            {
                _luaUpdateSecond = LuaManager.mainState.GetFunction("G_MarchManager.UpdateEverySecond");
            }
            
            if (_luaUpdateSecond != null && _ct - _lastUpdateTime > 0.5f)
            {
                try
                {
                    _luaUpdateSecond.Call();
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
                _lastUpdateTime = _ct;
            }
            UpdateEverySecondMarker.End();

            luaMarchManagerUpdateMarker.Begin();
            if (_luaUpdate != null)
            {
                try
                {
                    _luaUpdate.Func<float,long,int>(_ct,TimeUtils.GetServerTimeMs());
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
            }

            luaMarchManagerUpdateMarker.End();

            Profiler.BeginSample("marchTest.Update");
            //if (_luaMarchTestUpdate != null)
            //{
            //    Vector3 centerPosition = BattleUtils.GetCameraCenterPosition();
            //    _luaMarchTestUpdate.Call(Time.time, centerPosition);
            //}

            Profiler.EndSample();

            Profiler.BeginSample("Other");


//            ThrowableManager.Instance?.Update();
            RTSBattleEffectManager.Instance?.Update();
            
            // 调试功能，这里监视几个变量

            // 部队总数
            //UWAEngine.LogValue("troop", ArmyManager.Instance.MarchManager.Count);
#if UNITY_EDITOR
            //ArmyManager.Instance.ResourceManager.Log();
            MarchHelper.fixTradeTruckPath = FixTradeTruckPath;
#endif




            Profiler.EndSample();

#if UNITY_EDITOR

            if (IsShowEdidorButton)
            {
                if (tempScale != SoldierScale || isChanged)
                {
                    if (ArmyManager.Instance != null)
                    {
                        tempScale = SoldierScale;
                        isChanged = false;
                        SquareDataManager.Instance.EditorResetScale();
                        SquareDataManager.Instance.ResetSoldierShadowPosition();
                    }
                }
            }
#endif
            if (!RTSLuaCallCSharpManager.isArmyEnabled && !isDisableUpdate && ArmyManager.Instance!=null && ArmyManager.Instance.MarchManager != null)
            {
                isDisableUpdate = true;
                if (ArmyManager.SpriteParticleSystemManager!=null)
                {
                    ArmyManager.SpriteParticleSystemManager.SetAllParticleEnable(false);
                }
                var root = ArmyManager.Instance.MarchManager.GetRoot();
                if (root!=null)
                {
                    root.gameObject.SetActive(false);
                }
            }
           
#if UNITY_EDITOR
            if (Input.GetKeyDown(KeyCode.Space))
            {
                var ray = WorldCameraManager.mainCamera.ScreenPointToRay(Input.mousePosition);
                var objects = Physics.RaycastAll(ray);
                for (int i = 0; i < objects.Length; i++)
                {
                    Debug.LogError("射线检测 物理"+ i + " " + objects[i].collider.name);
                }
                PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
                pointerEventData.position = Input.mousePosition;
                List<RaycastResult> result = new List<RaycastResult>();
                EventSystem.current.RaycastAll(pointerEventData,result);
                for (int i = 0; i < result.Count; i++)
                {
                    Debug.LogError("射线检测 UI"+ i + " " + result[i].gameObject.name);
                }
            }
#endif
        }

        private void LateUpdate()
        {
            MarchBesiegeManager.Instance.LateUpdate();
            SquareDataManager.Instance.LateUpdate();
        }
        public void Dispose()
        {
            SquareDataManager.Instance.Dispose();
            _luaUpdate = null;
            _luaUpdateSecond = null;
            Instance = null;
        }

        private void OnDestroy()
        {
            _flyTextManager?.Dispose();
            _flyTextManager = null;
            SquareDataManager.Instance.Dispose();
            //Timers.inst.Remove(BattleSync);
        }
    }
}
